package com.jeepig.common.utils.file;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.AccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.jeepig.common.config.JeepigConfig;
import com.jeepig.common.config.OssConfig;
import com.jeepig.common.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;

/**
 * 阿里云上传
 */
public class OssUploadUtils {

    private static final Logger logger = LoggerFactory.getLogger(OssUploadUtils.class);

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static String upload(String filePath , InputStream inputStream,String fileName){
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(OssConfig.getAccessKeyId(), OssConfig.getAccessKeySecret());
        //创建ossClient对象
        OSS ossClient = new OSSClientBuilder().build(OssConfig.getEndpoint(), credentialsProvider);
        try {
            String bucketName = OssConfig.getBucketName();
            String objectName = FileUploadUtils.getPathFileName(filePath, fileName);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,objectName.substring(1), inputStream);
            ossClient.putObject(putObjectRequest);
            return objectName;
        } catch (OSSException oe) {
            logger.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.error("Error Message:" + oe.getErrorMessage());
            logger.error("Error Code:" + oe.getErrorCode());
            logger.error("Request ID:" + oe.getRequestId());
            logger.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            logger.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            logger.error("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            logger.error("上传失败{}", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
